package com.yangchoi.lib_base.network.interceptor

import com.yangchoi.lib_base.utils.CookieUtil
import com.yangchoi.lib_base.utils.DataStoreUtil
import okhttp3.Interceptor
import okhttp3.Response

// 写入cookie到缓存
class WriteCookieInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val response = chain.proceed(request)
        val requestUrl = request.url.toString()
        val domain = request.url.host
        //cookie可能有多个，都保存下来
        if ((requestUrl.contains("/user/login") || requestUrl.contains("/user/register"))) {
            val cookies = response.headers("set-cookie")
            val cookie = CookieUtil.encodeCookie(cookies)
            CookieUtil.saveCookie(requestUrl, domain, cookie)
        }
        if (requestUrl.contains("/user/logout/json")){
            DataStoreUtil.clearSync()
        }
        return response
    }
}